package cn.duli.xianer.shiro;

import cn.duli.xianer.pojo.UserLoginAuths;
import cn.duli.xianer.pojo.Users;
import cn.duli.xianer.service.UserLoginAuthsService;
import cn.duli.xianer.service.UsersService;
import cn.duli.xianer.utils.JWTUtil;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;

@Service
public class MyRealm extends AuthorizingRealm {

    private static final Logger LOGGER = LogManager.getLogger(MyRealm.class);

    @Autowired
    public UsersService usersService;

    @Autowired
    public UserLoginAuthsService userLoginAuthsService;

    /**
     * 大坑！，必须重写此方法，不然Shiro会报错
     */
    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof JWTToken;
    }

    /**
     * （授权）
     * 只有当需要检测用户权限的时候才会调用此方法，例如checkRole,checkPermission之类的
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        String identifier = JWTUtil.getIdentifier(principals.toString());
        UserLoginAuths userLoginAuth = userLoginAuthsService.findByIdentifier(identifier);
        // 添加角色和权限
        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
        // 添加角色
        simpleAuthorizationInfo.addRole(usersService.findById(userLoginAuth.getUlaUid()).getuRole());
//        Set<String> permission = new HashSet<>(Arrays.asList(user.getuPerms().split(",")));
        // 添加权限
//        simpleAuthorizationInfo.addStringPermissions(permission);
        return simpleAuthorizationInfo;
    }

    /**
     * （认证）
     * 默认使用此方法进行用户名正确与否验证，错误抛出异常即可。
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken auth) throws AuthenticationException {
        String token = (String) auth.getCredentials();
        // identifier，用于和数据库进行对比
        String identifier = JWTUtil.getIdentifier(token);
        if (identifier == null) {
            throw new AuthenticationException("token invalid");
        }

        UserLoginAuths userLoginAuth = userLoginAuthsService.findByIdentifier(identifier);
        if (userLoginAuth == null) {
            throw new AuthenticationException("User didn't existed!");
        }

        if (! JWTUtil.verify(token, identifier, userLoginAuth.getUlaCredential())) {
            throw new AuthenticationException("identifier or getUlaCredential error");
        }

        return new SimpleAuthenticationInfo(token, token, "my_realm");
    }
}
